package com.dkts.oil.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import com.dkts.oil.router.param.PathInfo;

public class GeoJsonBuilder {

    /**
     * 将 PathInfo 列表转换为 MultiLineString GeoJSON
     * @param pathInfos 路径信息列表
     * @return GeoJSON 字符串
     */
    public static String buildGeoJsonFromPaths(List<PathInfo> pathInfos) {
        JSONObject geoJson = new JSONObject();
        geoJson.put("type", "FeatureCollection");

        JSONArray features = new JSONArray();

        for (PathInfo pathInfo : pathInfos) {
            PathInfo.RoutePoints points = pathInfo.getPoints();
            if (points == null || points.getCoordinates() == null) {
                continue;
            }

            JSONArray coordinates = points.getCoordinates();

            JSONObject feature = new JSONObject();
            feature.put("type", "Feature");

            JSONObject geometry = new JSONObject();
            geometry.put("type", "LineString");
            geometry.put("coordinates", coordinates);

            feature.put("geometry", geometry);

            JSONObject properties = new JSONObject();
            properties.put("distance", pathInfo.getDistance());
            properties.put("time", pathInfo.getTime());
            feature.put("properties", properties);

            features.add(feature);
        }

        geoJson.put("features", features);

        return geoJson.toJSONString();
    }

    /**
     * 将 PathInfo 列表合并成一个 MultiLineString GeoJSON
     * @param pathInfos 路径信息列表
     * @return GeoJSON 字符串
     */
    public static String buildMultiLineGeoJson(List<PathInfo> pathInfos) {
        JSONObject geoJson = new JSONObject();
        geoJson.put("type", "Feature");

        JSONObject geometry = new JSONObject();
        geometry.put("type", "MultiLineString");

        JSONArray multiCoordinates = new JSONArray();

        for (PathInfo pathInfo : pathInfos) {
            PathInfo.RoutePoints points = pathInfo.getPoints();
            if (points == null || points.getCoordinates() == null) {
                continue;
            }

            JSONArray coordinates = points.getCoordinates();
            multiCoordinates.add(coordinates);
        }

        geometry.put("coordinates", multiCoordinates);

        geoJson.put("geometry", geometry);
        geoJson.put("properties", new JSONObject());

        return geoJson.toJSONString();
    }

}
